﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Text;
using System.Collections.Generic;

namespace YXShop.Web.membercenter.product
{
    public partial class make_convert_orders : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (ChangeHope.WebPage.PageRequest.GetFormString("Option") != "")
                {
                    string types = Request.Form["Option"].Trim();
                    if (types == "Province")
                    {
                        string ProvinceId = Request.Form["ProvinceId"].Trim();
                        Response.Write(YXShop.Common.Province.Provinces_City("", ProvinceId));
                    }
                    if (types == "Citys")
                    {
                        string CitysId = Request.Form["CitysId"].Trim();
                        Response.Write(YXShop.Common.Province.Provinces_Borough("", CitysId));
                    }
                    Response.End();
                    return;
                }

                int ProId = 0;
                int OrderType = ChangeHope.WebPage.PageRequest.GetQueryInt("ConvertOrderType");
                if (OrderType == 1)
                {
                    //拍卖转成订单
                    int AuctionBidId = ChangeHope.WebPage.PageRequest.GetQueryInt("AuctionBidId");
                    if (AuctionBidId > 0)
                    {
                        YXShop.BLL.Product.Product_Auction_Bid pabbll = new YXShop.BLL.Product.Product_Auction_Bid();
                        YXShop.Model.Product.Product_Auction_Bid pabmodel = pabbll.GetModel(AuctionBidId);
                        if (pabmodel != null)
                        {
                            ProId = Convert.ToInt32(pabmodel.productid.ToString());
                            ViewState["ProductId"] = ProId;
                        }
                        else
                        {
                            ChangeHope.WebPage.Script.AlertAndGoBack("拍卖转成订单失败,请与运营商联系.");
                        }
                        this.ConsigneeInfo(AuctionBidId, OrderType);
                    }
                }
                else if(OrderType==2)
                {
                    //团购转成订单
                    int GroupBuySignupId = ChangeHope.WebPage.PageRequest.GetQueryInt("GroupBuySignupId");
                    int SendGroupBuyId = ChangeHope.WebPage.PageRequest.GetQueryInt("SendGroupBuyId");
                    if (GroupBuySignupId > 0)
                    {
                        YXShop.BLL.Product.Product_SendGroupBuyInfo sgibll = new YXShop.BLL.Product.Product_SendGroupBuyInfo();
                        YXShop.Model.Product.Product_SendGroupBuyInfo sgimodel = sgibll.GetModelID(SendGroupBuyId);
                        if (sgimodel != null)
                        {
                            ProId = Convert.ToInt32(sgimodel.ProductID);
                            ViewState["ProductId"] = ProId;
                        }
                        else
                        {
                            ChangeHope.WebPage.Script.AlertAndGoBack("团购转成订单失败.");
                        }
                        this.ConsigneeInfo(GroupBuySignupId, OrderType);
                    }
                }
                //查询商家
                string UserTypeId = "0";
                string UserId = "0";
                YXShop.BLL.Product.ProductInfo pibll = new YXShop.BLL.Product.ProductInfo();
                YXShop.Model.Product.ProductInfo pimodel = pibll.GetModel(ProId);
                if (pimodel != null)
                {
                    UserTypeId = pimodel.pro_PutoutType.ToString();
                    UserId = pimodel.pro_PutoutID.ToString();
                }

                this.OnlinePaymentInfo(ProId, UserTypeId, UserId);
                this.BankPaymentInfo(ProId, UserTypeId, UserId);
                this.DeliveryInfo(ProId, UserTypeId, UserId);
                this.Provinces.Text = this.ProvincesStr();
            }
        }

        #region 收货信息
        private void ConsigneeInfo(int Id, int OrderType)
        {
            if (OrderType == 1)
            {
                YXShop.BLL.Product.Product_Auction_Bid pabbll = new YXShop.BLL.Product.Product_Auction_Bid();
                YXShop.Model.Product.Product_Auction_Bid pabmodel = pabbll.GetModel(Id);
                if (pabmodel != null)
                {
                    this.txtName.Text = pabmodel.username;
                    this.txtName.ReadOnly = true;
                    this.txtTel.Text = pabmodel.tel;
                    this.txtTel.ReadOnly = true;
                    this.txtMobile.Text = pabmodel.phone;
                    this.txtMobile.ReadOnly = true;
                    this.txtCode.Text = pabmodel.zip;
                    this.txtCode.ReadOnly = true;
                    this.txtAddress.Text = pabmodel.address;
                    this.txtAddress.ReadOnly = true;
                }
            }
            else if (OrderType == 2)
            {
                YXShop.BLL.Product.GroupBuy_OnlineSignUpInfo osibll = new YXShop.BLL.Product.GroupBuy_OnlineSignUpInfo();
                YXShop.Model.Product.GroupBuy_OnlineSignUpInfo osimodel = osibll.GetModelID(Id);
                if (osimodel != null)
                {
                    this.txtName.Text = osimodel.Name;
                    this.txtTel.Text = osimodel.Tel;
                    this.txtMobile.Text = "";
                    this.txtCode.Text = "";
                    this.txtAddress.Text = osimodel.Address;
                }
            }
        }
        #endregion

        #region 省份信息
        private string ProvincesStr()
        {
            string Province = string.Empty;
            string City = string.Empty;
            string Borough = string.Empty;
            string reStr = string.Empty;
            reStr += "<table>";
            reStr += "<tr>";
            reStr += "<td>";
            reStr += YXShop.Common.Province.Provincess(Province);
            reStr += "</td>";
            reStr += "<td><div id='CityDiv'>";
            reStr += YXShop.Common.Province.Provinces_City(City, Province);
            reStr += "</div></td>";
            reStr += "<td><div id='City2Div'>";
            reStr += YXShop.Common.Province.Provinces_Borough(Borough, City);
            reStr += "</div></td>";
            reStr += "</tr>";
            reStr += "</table>";
            return reStr;
        }
        #endregion

        #region 在线支付信息
        private void OnlinePaymentInfo(int productid, string UserTypeId, string UserId)
        {
            YXShop.Common.SysParameter sp = new YXShop.Common.SysParameter();
            StringBuilder shtml = new StringBuilder();
            YXShop.BLL.SystemInfo.TerraceManage tmbll = new YXShop.BLL.SystemInfo.TerraceManage();
            ChangeHope.DataBase.DataByPage dbp = null;
            if (sp.IsPayMentWebOperation)
            {
                dbp = tmbll.GetList(" [order by] payment_id asc", 10, " and payment_putouttypeid=0");
            }
            else
            {
                if (UserTypeId == "0")
                {
                    dbp = tmbll.GetList(" [order by] payment_id asc", 10, " and payment_putouttypeid=0");
                }
                else
                {
                    dbp = tmbll.GetList(" [order by] payment_id asc", 10, " and payment_putouttypeid=1 and payment_putoutid=" + UserId + "");
                }
            }
            if (dbp.DataReader == null)
            {
                dbp = tmbll.GetList(" [order by] payment_id asc", 10, " and payment_putouttypeid=0");
            }
            if (dbp.DataReader != null)
            {
                shtml.Append("<table width=\"100%\" border=\"0\" cellspacing=\"1\" cellpadding=\"1\">");
                while (dbp.DataReader.Read())
                {

                    shtml.Append("<tr>");
                    shtml.Append("<td><input type=\"radio\" name=\"paymentMethod\" value=\"" + dbp.DataReader["payment_id"].ToString() + "\" onclick=\"changePM(this)\" />" + dbp.DataReader["payment_name"].ToString() + "</td>");
                    shtml.Append("</tr>");

                }
                shtml.Append("</table>");
                this.lblList.Text = shtml.ToString();
            }
        }
        #endregion

        #region 银行信息
        private void BankPaymentInfo(int ProductId, string UserTypeId, string UserId)
        {
            YXShop.Common.SysParameter sp = new YXShop.Common.SysParameter();
            StringBuilder shtml = new StringBuilder();

            YXShop.BLL.SystemInfo.BankAccount bibll = new YXShop.BLL.SystemInfo.BankAccount();
            ChangeHope.DataBase.DataByPage dbp = null;
            if (sp.IsPayMentWebOperation)
            {
                dbp = bibll.GetList(" [order by] bank_id asc ", 10, " and bank_putouttypeid=0");
            }
            else
            {
                if (UserTypeId == "0")
                {
                    dbp = bibll.GetList(" [order by] bank_id asc ", 10, " and bank_putouttypeid=0");
                }
                else
                {
                    dbp = bibll.GetList(" [order by] bank_id asc ", 10, " and bank_putouttypeid=1 and bank_putoutID=" + UserId + "");
                }
            }
            if (dbp.DataReader == null)
            {
                dbp = bibll.GetList(" [order by] bank_id asc ", 10, " and bank_putouttypeid=0");
            }
            if (dbp.DataReader != null)
            {
                shtml.Append("<table width=\"100%\" border=\"0\" cellspacing=\"1\" cellpadding=\"1\">");
                while (dbp.DataReader.Read())
                {
                    string url = sp.DummyPaht + "images/NaughtImages.gif";
                    if (dbp.DataReader["bank_icon"].ToString() != string.Empty)
                    {
                        url = sp.DummyPaht + dbp.DataReader["bank_icon"].ToString();
                    }
                    shtml.Append("<tr>");
                    shtml.Append("<td><input type=\"radio\" name=\"paymentMethod\" value=\"" + dbp.DataReader["bank_id"].ToString() + "\" onclick=\"changePM(this)\" /><img src=" + url + " width='180' height='40'>开户行：" + dbp.DataReader["bank_bankac"].ToString() + "户名：" + dbp.DataReader["bank_name"].ToString() + "帐号：" + dbp.DataReader["bank_number"].ToString() + "</td>");
                    shtml.Append("</tr>");

                }
                shtml.Append("</table>");
            }
            this.lblBankList.Text = shtml.ToString();
        }
        #endregion

        #region 配送信息
        private void DeliveryInfo(int ProductId, string UserTypeId, string UserId)
        {
            YXShop.Common.SysParameter sp = new YXShop.Common.SysParameter();
            StringBuilder shtmldi = new StringBuilder();
            YXShop.BLL.Product.Deliver datadi = new YXShop.BLL.Product.Deliver();
            List<YXShop.Model.Product.Deliver> data = null;
            if (sp.IsPayMentWebOperation)
            {
                data = datadi.GetAll(" putouttyid=0");
            }
            else
            {

                if (UserTypeId == "0")
                {
                    data = datadi.GetAll(" putouttyid=0");
                }
                else
                {
                    data = datadi.GetAll(" putouttyid=1 and payment_putoutid=" + UserId + "");
                }
            }
            if (data.Count == 0)
            {
                data = datadi.GetAll(" putouttyid=0");
            }


            if (data.Count > 0)
            {
                shtmldi.Append("<table width=\"100%\" border=\"0\" cellspacing=\"1\" cellpadding=\"1\">");
                foreach (YXShop.Model.Product.Deliver da in data)
                {
                    shtmldi.Append("<tr><td><input type=\"radio\" id=\"deilver\" name=\"deilver\" value=\"" + da.ID + "\" onclick=\"chooseDeil(this)\" />" + da.Name + "</td></tr>");

                }
                shtmldi.Append("</table>");
            }
            this.DeliveryInfoList.Text = shtmldi.ToString();
        }
        #endregion

        #region 生成订单
        protected void butSave_Click(object sender, EventArgs e)
        {
            SaveInfo(Convert.ToInt32(ViewState["ProductId"].ToString()));
        }
        private void SaveInfo(int ProductId)
        {
            int OrderType = ChangeHope.WebPage.PageRequest.GetQueryInt("ConvertOrderType");
            decimal price = 0;
            int count = 0;
            if (OrderType == 1)
            {
                int AuctionBidId = ChangeHope.WebPage.PageRequest.GetQueryInt("AuctionBidId");
                YXShop.BLL.Product.Product_Auction_Bid pabbll = new YXShop.BLL.Product.Product_Auction_Bid();
                YXShop.Model.Product.Product_Auction_Bid pabmodel = pabbll.GetModel(AuctionBidId);
                if (pabmodel != null)
                {
                    price = Convert.ToDecimal(pabmodel.price);
                    count = Convert.ToInt32(pabmodel.count);
                }
            }
            else
            {
                int GroupBuySignupId = ChangeHope.WebPage.PageRequest.GetQueryInt("GroupBuySignupId");
                YXShop.BLL.Product.GroupBuy_OnlineSignUpInfo osubll = new YXShop.BLL.Product.GroupBuy_OnlineSignUpInfo();
                YXShop.Model.Product.GroupBuy_OnlineSignUpInfo osumodel = osubll.GetModelID(GroupBuySignupId);
                if (osumodel != null)
                {
                    YXShop.BLL.Product.Product_IntegratePurchas ipbll = new YXShop.BLL.Product.Product_IntegratePurchas();
                    YXShop.Model.Product.Product_IntegratePurchas ipmodel = ipbll.GetModelProductID(ProductId);
                    price = 0;
                    count = Convert.ToInt32(osumodel.Count);
                    if (ipmodel != null)
                    {
                        string[] LadderCount = ipmodel.LadderCount.Split(',') ;
                        string[] LadderCountSort = ChangeHope.Common.SortHelper.BubbleSort(LadderCount);
                        string[] LadderPrice = ipmodel.LadderPrice.Split(',');
                        for (int k = LadderCount.Length - 1; k >= 0; k--)
                        {
                            if (Convert.ToInt32(LadderCountSort[k]) <= count)
                            {
                                price =Convert.ToDecimal(LadderPrice[k]);
                            }
                        }
                    }
                    
                }
            }
            YXShop.Common.SysParameter sp = new YXShop.Common.SysParameter();
            string OrderStr = sp.OrderId;
            string username = Session["MemberName"].ToString();
            YXShop.BLL.Product.ProductInfo pibll = new YXShop.BLL.Product.ProductInfo();
            YXShop.Model.Product.ProductInfo pimodel = pibll.GetModel(ProductId);
            if (pimodel != null)
            {
                BLL.Member.MemberInfo user = new YXShop.BLL.Member.MemberInfo();
                BLL.Order.Orders bll = new YXShop.BLL.Order.Orders();
                Model.Order.Orders model = new YXShop.Model.Order.Orders();
                model.UserId = username;
                model.WhetherCouAndinte = "0";
                model.ConsigneeName = ChangeHope.Common.StringHelper.InputTexts(this.txtName.Text);
                model.ConsigneeRealName = ChangeHope.Common.StringHelper.InputTexts(this.txtName.Text);
                model.ConsigneeAddress = ChangeHope.Common.StringHelper.InputTexts(this.txtAddress.Text);
                model.ConsigneeTel = ChangeHope.Common.StringHelper.InputTexts(this.txtTel.Text);
                model.ConsigneeFax = ChangeHope.Common.StringHelper.InputTexts(this.txtFax.Text);
                model.ConsigneeZip = ChangeHope.Common.StringHelper.InputTexts(this.txtCode.Text);
                model.ConsigneeProvince = ChangeHope.WebPage.PageRequest.GetFormString("Provinces");
                model.ConsigneePhone = ChangeHope.Common.StringHelper.InputTexts(this.txtMobile.Text);
                model.ConsigneeEmail = ChangeHope.Common.StringHelper.InputTexts(this.txtMail.Text);
                model.Carriage = (decimal)ChangeHope.WebPage.PageRequest.GetFormInt("deilver");
                model.PaymentType = ChangeHope.WebPage.PageRequest.GetFormString("PaymentType");

                model.Payment = Decimal.Parse(ChangeHope.WebPage.PageRequest.GetFormString("paymentMethod"));
                model.FactPrice = 0;
                model.Invoice = 0;
                model.OrderDate = System.DateTime.Now;
                model.OrderId = "";
                model.OrderStatus = 0;
                model.ParvalueAndInte = 0;

                model.ShopDate = System.DateTime.Now;
                model.TotalPrice = 0;
                model.OrderType = OrderType;
                //下面是判断各种情况的出现
                //第一种情况，判断订单的接收方

                YXShop.Common.SysParameter sys = new YXShop.Common.SysParameter();
                bool ispaymentweboperation = sys.IsPayMentWebOperation;
                //网站运营商 1
                //单独的商家 0
                double allprice = 0.0;
                decimal weight = 0;
                //读取该人员所有的购物车。

                BLL.Product.ProductInfo bllProductInfo = new YXShop.BLL.Product.ProductInfo();
                Model.Product.ProductInfo modelProductInfo = new YXShop.Model.Product.ProductInfo();
                YXShop.TemplateAction.Common common = new YXShop.TemplateAction.Common();
                BLL.Order.OrderProduct bllOrderProduct = new YXShop.BLL.Order.OrderProduct();
                Model.Order.OrderProduct modelOrderProduct = new YXShop.Model.Order.OrderProduct();

                BLL.Product.Deliver deliverBll = new YXShop.BLL.Product.Deliver();
                Model.Product.Deliver deliverModel = deliverBll.GetModelByID((int)model.Carriage);
                if (ispaymentweboperation)
                {
                    model.SaleUserID = "0";
                    model.SaleUserType = "0";
                    model.Courier = 0;
                    model.BusinessmanID = "0";
                    model.ReceiverId = "0";
                    model.OrderId = OrderStr;
                    model.TotalPrice = 0;
                    model.Remark = "";
                    int id = bll.Add(model);
                    //商品信息
                    //foreach (System.Data.DataRow row in cartlist.Rows)
                    //{
                    modelOrderProduct.AddTime = System.DateTime.Now;
                    modelOrderProduct.OrderId = id;
                    modelOrderProduct.ProId = int.Parse(pimodel.pro_ID.ToString());
                    //modelProductInfo = bllProductInfo.GetModel((int)modelOrderProduct.ProId);
                    modelOrderProduct.ProClass = pimodel.pro_CID;
                    modelOrderProduct.ProImg = pimodel.pro_Thumbnail;
                    modelOrderProduct.ProName = pimodel.pro_Name;
                    weight += (decimal)pimodel.pro_Weight;
                    modelOrderProduct.ProNum = Decimal.Parse(count.ToString());
                    modelOrderProduct.ProOtherPara = "";
                    modelOrderProduct.ProPrice = (decimal)price;
                    allprice += (double)price * (double)count;
                    bllOrderProduct.Add(modelOrderProduct);
                    //}
                    if (weight < deliverModel.InceptWeight)
                    {
                        model.Courier = deliverModel.InceptPrice;
                    }
                    else
                    {
                        model.Courier = deliverModel.InceptPrice + ((weight - deliverModel.InceptWeight) / deliverModel.AddWeightLadder) * deliverModel.AddPriceLadder;
                    }

                    model.TotalPrice = (decimal)allprice;
                    model.FactPrice = (decimal)allprice + model.Courier;
                    model.Id = id;
                    bll.Update(model);
                }
                else
                {
                    model.SaleUserID = "0";
                    model.SaleUserType = "1";
                    model.Courier = 0;
                    model.BusinessmanID = "0";
                    model.ReceiverId = "0";
                    model.OrderId = OrderStr;
                    model.TotalPrice = 0;
                    model.Remark = "";
                    int id = bll.Add(model);
                    //商品信息
                    //foreach (System.Data.DataRow row in cartlist.Rows)
                    //{
                    modelOrderProduct.AddTime = System.DateTime.Now;
                    modelOrderProduct.OrderId = id;
                    modelOrderProduct.ProId = int.Parse(pimodel.pro_ID.ToString());
                    //modelProductInfo = bllProductInfo.GetModel((int)modelOrderProduct.ProId);
                    modelOrderProduct.ProClass = pimodel.pro_CID;
                    modelOrderProduct.ProImg = pimodel.pro_Thumbnail;
                    modelOrderProduct.ProName = pimodel.pro_Name;
                    weight += (decimal)pimodel.pro_Weight;
                    modelOrderProduct.ProNum = Decimal.Parse(count.ToString());
                    modelOrderProduct.ProOtherPara = "";
                    modelOrderProduct.ProPrice = price;
                    allprice += (double)price * (double)count;
                    bllOrderProduct.Add(modelOrderProduct);
                    //}
                    if (weight < deliverModel.InceptWeight)
                    {
                        model.Courier = deliverModel.InceptPrice;
                    }
                    else
                    {
                        model.Courier = deliverModel.InceptPrice + ((weight - deliverModel.InceptWeight) / deliverModel.AddWeightLadder) * deliverModel.AddPriceLadder;
                    }

                    model.TotalPrice = (decimal)allprice;
                    model.FactPrice = (decimal)allprice + model.Courier;
                    model.Id = id;
                    bll.Update(model);

                }
                string ReturnUrl = YXShop.TemplateAction.Common.UrlStr("paymentorders", "OrderId=" + OrderStr + "", "product/");
                HttpContext.Current.Response.Redirect(ReturnUrl);
            }
            else
            {
                Response.Write("对不起，您还没有购买任何商品");
            }
        }
        #endregion
    }
}
